import re
from collections import defaultdict

log_file = 'C:\\Users\\mazhe\\Desktop\\gpu_log.txt'  # 你的日志文件路径

# 存储数据
gpu_usage = defaultdict(list)     # 物理 GPU 的利用率
vgpu_usage = defaultdict(list)    # vGPU 的利用率

with open(log_file, 'r', encoding='utf-8') as f:
    lines = f.readlines()

current_gpu = None

for line in lines:
    # 匹配物理 GPU 的利用率
    gpu_match = re.search(r'\|\s+(\d+)\s+Tesla.*?\|\s+\S+\s+\|\s+(\d+)%', line)
    if gpu_match:
        gpu_id = gpu_match.group(1)
        gpu_util = int(gpu_match.group(2))
        gpu_usage[gpu_id].append(gpu_util)
        current_gpu = gpu_id
        continue

    # 匹配 vGPU 的利用率
    vgpu_match = re.search(r'\|\s+\d+\s+GRID.*?\|\s+\d+\s+\S+\s+\|\s+(\d+)%', line)
    if vgpu_match and current_gpu is not None:
        vgpu_util = int(vgpu_match.group(1))
        vgpu_id = re.search(r'GRID.*?\s+\|\s+(\d+)', line).group(1)  # VM ID 作为 key
        vgpu_usage[vgpu_id].append(vgpu_util)

# 统计结果
def calc_stats(data_dict, label):
    print(f'\n===== {label} 统计结果 =====')
    for id, values in data_dict.items():
        max_util = max(values)
        avg_util = sum(values) / len(values)
        print(f'{label} {id}: 峰值 = {max_util}%, 平均值 = {avg_util:.2f}%')

calc_stats(gpu_usage, '物理GPU')
calc_stats(vgpu_usage, 'vGPU')
